//
//  WordsCollectionListViewController.swift
//  ShimaPlayer
//
//  Created by michael on 2025/7/18.
//

import UIKit

enum WordListType {
    case unLearned
    case learned
    case all
}

class WordsCollectionListViewController: UIViewController {

    var wordListType: WordListType = .unLearned
    
    var list: [WordItemModel] = [WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 WordItemModel(original: "案内します③", translation: "陪同，带路", type: "他サ"),
                                 ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    
    func setupUI() {
        view.backgroundColor = UIColor(hexString: "#FFFFFF")

        let titleLabel = UILabel()
        titleLabel.text = "单词收藏"
        titleLabel.textColor = UIColor(hexString: "#2F2D51")
        titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(5)
            make.leading.equalToSuperview().offset(20)
        }
        
        // 使用泛型 RadioGroupView 示例
        let radioGroup = RadioGroupView<WordListTypeOptionView>()
        
        // 设置初始选择索引
        radioGroup.selectedIndex = 0
        
        // 配置选中指示器
        radioGroup.indicatorConfig = RadioGroupIndicatorConfig(
            style: .underline(width: 20, height: 2),
            color: UIColor(hexString: "#15CC9D") ?? .systemBlue,
            animationDuration: 0.25,
            animationOptions: [.curveEaseInOut]
        )
        
        // 配置选项数据
        let options: [WordListType] = [.unLearned, .learned, .all]
        radioGroup.configure(with: options) { data in
            return WordListTypeOptionView()
        }
        
        // 设置选择回调
        radioGroup.onSelectionChanged = { [weak self] index, selectedType in
            guard let self = self, let type = selectedType else { return }
            self.wordListType = type
            print("选择了: \(type), 索引: \(index)")
        }
        
        view.addSubview(radioGroup)
        radioGroup.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.horizontalEdges.equalToSuperview().inset(40)
            make.height.equalTo(44)
        }
        
        let tableView = TableView<WordItemModel, WordItemModel, SwipeableCell<WordItemCellContent>>(style: .grouped)
            .backgroundColor(view.backgroundColor)
            .rowHeight(85)
            .separatorStyle(.singleLine)
            .separatorInset(UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16))
            .sections([])
            .rowsForSection { section in self.list }
            .configureCell { cell, item, indexPath in
                cell.configure(with: item)
                cell.cornerRadius(10)
                cell.actionsContainerViewBackgroundColor(UIColor(hexString: "#15CC9D"))
                cell.enableShadow()
                cell.addAction(title: "加入\n已学习", backgroundColor: UIColor(hexString: "#15CC9D"), fontSize: 13, buttonWidth: 70) {
                        // Handle delete action
//                        self.items.remove(at: indexPath.row)
//                        tableView.deleteRows(at: [indexPath], with: .automatic)
                    }
            }

        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(radioGroup.snp.bottom).offset(21)
            make.horizontalEdges.equalToSuperview()
        }

        let actionButton = UIButton(type: .system)
        actionButton.setTitle("开始背词", for: .normal)
        actionButton.setTitleColor(UIColor(hexString: "#FFFFFF"), for: .normal)
        actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        actionButton.backgroundColor = UIColor(hexString: "#15CC9D")
        actionButton.layer.cornerRadius = 20
        actionButton.addTarget(self, action: #selector(actionButtonTapped), for: .touchUpInside)
        
        view.addSubview(actionButton)
        actionButton.snp.makeConstraints { make in
            make.top.equalTo(tableView.snp.bottom)
            make.horizontalEdges.equalToSuperview().inset(16)
            make.height.equalTo(40)
            make.bottom.equalToSuperview().inset(Size.bottomSafeAreaHeight)
        }
    }

    @objc func actionButtonTapped() {
        print("Action button tapped")
    }

}

class WordItemCellContent: UIView, SwipeableCellContent {
    
    private let originalLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16, weight: .medium)
        label.textColor = UIColor(hexString: "#1C1F1E")
        return label
    }()
    
    private let translationLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 13)
        label.textColor = UIColor(hexString: "#868F99")
        return label
    }()
    
    private let typeLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 9)
        label.textColor = UIColor(hexString: "#15CC9D")
        label.backgroundColor = UIColor(hexString: "#15CC9D")?.withAlphaComponent(0.1)
        label.layer.cornerRadius = 6.5
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        backgroundColor = UIColor(hexString: "#FFFFFF")
        
        addSubview(originalLabel)
        originalLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.leading.equalToSuperview().offset(16)
        }
        
        let stack = UIStackView(arrangedSubviews: [typeLabel, translationLabel])
        stack.axis = .horizontal
        stack.spacing = 4
        
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.top.equalTo(originalLabel.snp.bottom).offset(10)
            make.leading.equalToSuperview().offset(16)
        }
        
        typeLabel.snp.makeConstraints { make in
            make.height.equalTo(13)
        }
    }

    func configure<Model>(with model: Model) {
        if let item = model as? WordItemModel {
            originalLabel.text = item.original
            translationLabel.text = item.translation
            typeLabel.text = item.type
        }
    }   
}


// MARK: - 选项视图协议
protocol RadioOptionViewProtocol: UIView {
    associatedtype DataType
    
    var isSelected: Bool { get set }
    var data: DataType { get set }
    
    func configure(with data: DataType)
    func setSelected(_ selected: Bool, animated: Bool)
}

// MARK: - 选中指示器配置
struct RadioGroupIndicatorConfig {
    enum Style {
        case underline(width: CGFloat, height: CGFloat)
        case background(cornerRadius: CGFloat)
        case border(width: CGFloat, cornerRadius: CGFloat)
        case custom(view: UIView)
    }
    
    let style: Style
    let color: UIColor?
    let animationDuration: TimeInterval
    let animationOptions: UIView.AnimationOptions
    
    init(style: Style = .underline(width: 20, height: 2),
         color: UIColor? = UIColor(hexString: "#15CC9D"),
         animationDuration: TimeInterval = 0.3,
         animationOptions: UIView.AnimationOptions = [.curveEaseInOut]) {
        self.style = style
        self.color = color
        self.animationDuration = animationDuration
        self.animationOptions = animationOptions
    }
}

// MARK: - 泛型单选组视图
class RadioGroupView<OptionView: RadioOptionViewProtocol>: UIView {
    
    // MARK: - 公共属性
    var selectedIndex: Int = -1 {
        didSet {
            updateSelection(animated: true)
            updateIndicator(animated: true)
        }
    }
    
    var onSelectionChanged: ((Int, OptionView.DataType?) -> Void)?
    
    // MARK: - 指示器属性
    var indicatorConfig: RadioGroupIndicatorConfig? {
        didSet {
            setupIndicator()
            updateSelection(animated: true)
            updateIndicator(animated: true)
        }
    }
    
    // MARK: - 私有属性
    private var optionViews: [OptionView] = []
    private var optionData: [OptionView.DataType] = []
    private let stackView: UIStackView
    private var indicatorView: UIView?
    private var indicatorConstraints: [NSLayoutConstraint] = []
    
    // MARK: - 布局配置
    enum LayoutDirection {
        case horizontal
        case vertical
    }
    
    private let layoutDirection: LayoutDirection
    private let spacing: CGFloat
    private let distribution: UIStackView.Distribution
    
    // MARK: - 初始化
    init(direction: LayoutDirection = .horizontal, 
         spacing: CGFloat = 8, 
         distribution: UIStackView.Distribution = .fillEqually) {
        self.layoutDirection = direction
        self.spacing = spacing
        self.distribution = distribution
        
        self.stackView = UIStackView()
        
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI 设置
    private func setupUI() {
        stackView.axis = layoutDirection == .horizontal ? .horizontal : .vertical
        stackView.spacing = spacing
        stackView.distribution = distribution
        stackView.alignment = .fill
        
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    // MARK: - 公共方法
    func configure(with data: [OptionView.DataType], 
                  optionViewBuilder: (OptionView.DataType) -> OptionView) {
        // 清除现有视图
        clearOptions()
        
        // 保存数据
        self.optionData = data
        
        // 创建选项视图
        for (index, item) in data.enumerated() {
            let optionView = optionViewBuilder(item)
            optionView.configure(with: item)
            optionView.tag = index
            
            // 添加点击手势
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(optionTapped(_:)))
            optionView.addGestureRecognizer(tapGesture)
            optionView.isUserInteractionEnabled = true
            
            optionViews.append(optionView)
            stackView.addArrangedSubview(optionView)
        }
        
        // 设置默认选择
        if selectedIndex >= 0 && selectedIndex < optionViews.count {
            updateSelection(animated: false)
            // 在下一个运行循环中更新指示器，确保布局完成
            DispatchQueue.main.async { [weak self] in
                self?.updateIndicator(animated: false)
            }
        }
    }
    
    func selectOption(at index: Int, animated: Bool = true) {
        guard index >= 0 && index < optionViews.count else { return }
        selectedIndex = index
    }
    
    func getSelectedData() -> OptionView.DataType? {
        guard selectedIndex >= 0 && selectedIndex < optionData.count else { return nil }
        return optionData[selectedIndex]
    }
    
    // MARK: - 私有方法
    private func clearOptions() {
        optionViews.forEach { $0.removeFromSuperview() }
        optionViews.removeAll()
        optionData.removeAll()
    }
    
    private func updateSelection(animated: Bool) {
        for (index, optionView) in optionViews.enumerated() {
            let isSelected = index == selectedIndex
            optionView.setSelected(isSelected, animated: animated)
        }
    }
    
    @objc private func optionTapped(_ gesture: UITapGestureRecognizer) {
        guard let optionView = gesture.view as? OptionView else { return }
        let index = optionView.tag
        
        if index != selectedIndex {
            selectedIndex = index
            onSelectionChanged?(index, getSelectedData())
        }
    }
    
    // MARK: - 指示器方法
    private func setupIndicator() {
        // 移除旧的指示器
        indicatorView?.removeFromSuperview()
        NSLayoutConstraint.deactivate(indicatorConstraints)
        indicatorConstraints.removeAll()
        
        guard let config = indicatorConfig else { return }
        
        // 创建新的指示器
        let indicator: UIView
        
        switch config.style {
        case .underline(let width, let height):
            indicator = UIView()
            indicator.backgroundColor = config.color
            indicator.layer.cornerRadius = height / 2
            
        case .background(let cornerRadius):
            indicator = UIView()
            indicator.backgroundColor = config.color
            indicator.layer.cornerRadius = cornerRadius
            
        case .border(let width, let cornerRadius):
            indicator = UIView()
            indicator.backgroundColor = .clear
            indicator.layer.borderWidth = width
            indicator.layer.borderColor = config.color?.cgColor
            indicator.layer.cornerRadius = cornerRadius
            
        case .custom(let view):
            indicator = view
        }
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        indicatorView = indicator
        
        // 添加到视图层次
        insertSubview(indicator, at: 0)
        
        // 初始化约束（隐藏状态）
        setupInitialIndicatorConstraints()
        
        // 如果已有选中项，立即更新指示器
        if selectedIndex >= 0 {
            updateIndicator(animated: false)
        }
    }
    
    private func setupInitialIndicatorConstraints() {
        guard let indicator = indicatorView,
              let config = indicatorConfig else { return }
        
        switch config.style {
        case .underline(let width, let height):
            indicatorConstraints = [
                indicator.heightAnchor.constraint(equalToConstant: height),
                indicator.bottomAnchor.constraint(equalTo: stackView.bottomAnchor),
                indicator.widthAnchor.constraint(equalToConstant: width),
                indicator.centerXAnchor.constraint(equalTo: stackView.leadingAnchor)
            ]
            
        case .background(_), .border(_, _):
            indicatorConstraints = [
                indicator.topAnchor.constraint(equalTo: stackView.topAnchor),
                indicator.bottomAnchor.constraint(equalTo: stackView.bottomAnchor),
                indicator.widthAnchor.constraint(equalToConstant: 0),
                indicator.centerXAnchor.constraint(equalTo: stackView.leadingAnchor)
            ]
            
        case .custom(_):
            // 自定义视图的约束由用户自行处理
            indicatorConstraints = [
                indicator.centerXAnchor.constraint(equalTo: stackView.leadingAnchor),
                indicator.centerYAnchor.constraint(equalTo: stackView.centerYAnchor)
            ]
        }
        
        NSLayoutConstraint.activate(indicatorConstraints)
    }
    
    private func updateIndicator(animated: Bool) {
        guard let indicator = indicatorView,
              let config = indicatorConfig,
              selectedIndex >= 0,
              selectedIndex < optionViews.count else { return }
        
        let selectedOptionView = optionViews[selectedIndex]
        
        let updateConstraints = {
            NSLayoutConstraint.deactivate(self.indicatorConstraints)
            
            switch config.style {
            case .underline(let width, let height):
                self.indicatorConstraints = [
                    indicator.heightAnchor.constraint(equalToConstant: height),
                    indicator.bottomAnchor.constraint(equalTo: self.stackView.bottomAnchor),
                    // indicator.leadingAnchor.constraint(equalTo: selectedOptionView.leadingAnchor),
                    // indicator.trailingAnchor.constraint(equalTo: selectedOptionView.trailingAnchor)
                    indicator.centerXAnchor.constraint(equalTo: selectedOptionView.centerXAnchor),
                    indicator.widthAnchor.constraint(equalToConstant: width)
                ]
                
            case .background(_), .border(_, _):
                self.indicatorConstraints = [
                    indicator.topAnchor.constraint(equalTo: selectedOptionView.topAnchor),
                    indicator.bottomAnchor.constraint(equalTo: selectedOptionView.bottomAnchor),
                    indicator.leadingAnchor.constraint(equalTo: selectedOptionView.leadingAnchor),
                    indicator.trailingAnchor.constraint(equalTo: selectedOptionView.trailingAnchor)
                ]
                
            case .custom(_):
                self.indicatorConstraints = [
                    indicator.centerXAnchor.constraint(equalTo: selectedOptionView.centerXAnchor),
                    indicator.centerYAnchor.constraint(equalTo: selectedOptionView.centerYAnchor)
                ]
            }
            
            NSLayoutConstraint.activate(self.indicatorConstraints)
            self.layoutIfNeeded()
        }
        
        if animated {
            UIView.animate(withDuration: config.animationDuration,
                          delay: 0,
                          options: config.animationOptions,
                          animations: updateConstraints)
        } else {
            updateConstraints()
        }
    }
}

// MARK: - 示例选项视图实现
class WordListTypeOptionView: UIView, RadioOptionViewProtocol {
    typealias DataType = WordListType
    
    var isSelected: Bool = false
    var data: WordListType = .unLearned
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 15, weight: .medium)
        label.textAlignment = .center
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(titleLabel)

        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(12)
        }
    }
    
    func configure(with data: WordListType) {
        self.data = data
        
        switch data {
        case .unLearned:
            titleLabel.text = "未学习"
        case .learned:
            titleLabel.text = "已学习"
        case .all:
            titleLabel.text = "全部"
        }
        
        setSelected(isSelected, animated: false)
    }
    
    func setSelected(_ selected: Bool, animated: Bool) {
        isSelected = selected
        
        let updateUI = {
            self.titleLabel.textColor = UIColor(hexString: selected ? "#15CC9D" : "#868F99")
        }
        
        if animated {
            UIView.animate(withDuration: 0.2, animations: updateUI)
        } else {
            updateUI()
        }
    }
}

// MARK: - 指示器样式示例
/*
 使用不同指示器样式的示例：
 
 // 1. 下划线样式
 radioGroup.indicatorConfig = RadioGroupIndicatorConfig(
     style: .underline(height: 2),
     color: UIColor(hexString: "#15CC9D") ?? .systemBlue
 )
 
 // 2. 背景样式
 radioGroup.indicatorConfig = RadioGroupIndicatorConfig(
     style: .background(cornerRadius: 16),
     color: UIColor(hexString: "#15CC9D")?.withAlphaComponent(0.2) ?? .systemBlue.withAlphaComponent(0.2)
 )
 
 // 3. 边框样式
 radioGroup.indicatorConfig = RadioGroupIndicatorConfig(
     style: .border(width: 2, cornerRadius: 16),
     color: UIColor(hexString: "#15CC9D") ?? .systemBlue
 )
 
 // 4. 自定义样式
 let customIndicator = UIView()
 customIndicator.backgroundColor = UIColor(hexString: "#15CC9D")
 customIndicator.layer.cornerRadius = 4
 customIndicator.layer.shadowColor = UIColor.black.cgColor
 customIndicator.layer.shadowOffset = CGSize(width: 0, height: 2)
 customIndicator.layer.shadowOpacity = 0.1
 customIndicator.layer.shadowRadius = 4
 
 radioGroup.indicatorConfig = RadioGroupIndicatorConfig(
     style: .custom(view: customIndicator),
     animationDuration: 0.4,
     animationOptions: [.curveEaseInOut, .allowUserInteraction]
 )
 */
